<template>
  <div>
    <el-form class="input-form"
             label-position="right"
             label-width="120px"
             ref="editForm"
             :rules="propRules"
             :model="form"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="单号" prop="busKey">
            <span>{{strings.defaultString(form.busKey,'自动设置')}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="汇总日期" prop="busDate">
            <span>{{strings.defaultString(form.busDate,'自动设置')}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="汇总人/科室" prop="busUser">
            <span>{{form.busUser}}/{{form.deptName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" size="medium" type="textarea" :autosize="{ minRows: 1, maxRows: 4}"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="" label-width="0" style="text-align: center;">
            <span style="font-size: 18px">
              <span style="color: red;padding-right: 11px;">   院长审批限制: {{parameters.admAuditMax()}}</span>
              <span style="">  预估价合计: {{form.skuPriceAmount ? form.skuPriceAmount : 0}}</span>
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="询价起止" prop="bidEndDate">
            <el-date-picker
              :format="dates.defaultDatePattern"
              popper-class="el-date-range-picker-left320"
              v-model="bidDate"
              ref="bidDate"
              type="datetimerange"
              :disabled="checkBtnsDisable(1)"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="bidDateChange"
              :picker-options="dates.pickerOptions.timeIntervalWitchFutureDate"
              align="right">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="审批意见" prop="auditRemark">
            <el-input v-model="form.auditRemark" ref="auditRemark" type="textarea"  :autosize="{ minRows: 2, maxRows: 4}"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">

          <FortenEsign
            :fileSavePath="'usersign'"
            :fileRefTable="'usersign'"
            :fileRefId="utils.getCurrentUser().id"
            :propShowSave="true"
            :fileRefIdOnlyOne="'1'"
            ref="auditEsign"
            :propWidth="200"
            :propHeight="100"
          ></FortenEsign>
        </el-col>
      </el-row>
      <el-collapse v-model="activeNames">
        <!--准入申请列表-->
        <el-collapse-item title="准入审批列表" name="2">
          <data-view
            propViewKey="adm_matr_audit_item_withmatr"
            propViewForm="adm/matraudit/detail-inquiry.vue"
            :propInitData="form"
            :propAutoFetchData="false"
            :propHideFlowSelect="true"
            :propsDisableDbClick="true"
            :propReadonly="strings.defaultString(form.flowStatus,'start') != 'start'"
            ref="childDataViewAuditItem"
            class="data-view-inlinebtn data-view-noedit"
            :propCustomCols="propCustomCols"
            @extra-button-click="handleExtraButton"
            @select-change="selectChange"
            @after-load="afterLoad"
            :propPageSize="5"
            @after-delete="refreshRefs"
            :propFlowKey="propParent.propFlowKey"
          >
            <template #btns="{field,value,row}" >
              <el-button-group>
                <el-button type="primary" size="mini" @click="btnsCLick(1,row)" :disabled="checkBtnsDisable(1,row)">设置询价</el-button>
                <el-button type="" size="mini" @click="btnsCLick(2,row)" :disabled="checkBtnsDisable(2,row)">查看询价</el-button>
                <el-button type="primary" size="mini" @click="btnsCLick(3,row)" :disabled="checkBtnsDisable(3,row)">设置中标</el-button>
              </el-button-group>
            </template>
          </data-view>
          <data-view
            propViewKey="adm_matr_audit_item_withresult"
            :propAutoFetchData="false"
            ref="childDataViewAuditItemResult"
            style="display: none"
          >
          </data-view>
        </el-collapse-item>

        <!--流程审批记录-->
         <el-collapse-item title="流程审批记录" name="5">
           <flow-log
             ref="flowLog"
             :prop-flow-key="propParent.propFlowKey"
             :prop-bus-type="'adm_matr_audit'"
             :prop-bus-id="form.id"
             class="data-view-noflowbtn"
           />
         </el-collapse-item>
      </el-collapse>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable*/
export default {
  data() {
    return {
      form: {},
      viewData: {},
      activeNames: ['1', '2', '3', '5'],
      applyId: null,
      bidDate: [],
      dtlAddType: null
    }
  },
  methods: {
    //刷新申请材料
    fetchDataAuditItem() {
      //固定数据筛选参数
      let wrapper = this.$newWrapper().eq('auditId', this.form.id ? this.form.id : '-1')
      this.$refs.childDataViewAuditItem.setQueryWrapper(wrapper)
      this.$refs.childDataViewAuditItemResult.setQueryWrapper(wrapper)
    },
    afterLoad() {
      this.$refs.childDataViewAuditItem.editable = false

      let wrapper = this.$newWrapper().eq('auditId', this.form.id ? this.form.id : '-1')
      this.$refs.childDataViewAuditItemResult.setQueryWrapper(wrapper)

      this.setBtnShowHide()
    },
    refreshRefs() {
      this.utils.refreshRefs(this)
    },
    //行编辑选择事件
    async selectChange(param) {
      if (param.column.property == 'applyBusKey') {
        if (!this.form.id && this.form.id == null) {
          this.saveByAddRow = true
          await this.propParent.ocAsynSaveViewForm()
        }

        //转换属性
        let applyItem = []
        param.rows.forEach(ob => {
          ob.auditId = this.form.id
          ob.applyId = ob.applyId
          ob.applyItemId = ob.applyItemId
          if (this.dtlAddType == 'choiceMain') {
            ob.applyId = ob.id
          }
          applyItem.push(ob)
        })

        //批量添加
        this.utilVue.loadShow(true)
        this.$ajax.post('/adm/matr_audit_item/saveBatch', applyItem).then(resp => {
          if (resp.code == 0) {
            this.$message.success(resp.msg)
            this.fetchDataAuditItem()
            this.refreshRefs()
          }
          this.utilVue.loadHide()
        })
      }
    },
    //按钮事件
    handleExtraButton(para) {
      let wrapper = this.$newWrapper()
      //固定数据筛选参数
      let userParam = {
        viewKey: 'adm_matr_apply_select',
        checkType: 'checkbox',
        useMsg: '数据筛选条件：未参与准入审批的准入申请单'
      }

      switch(para.button.key) {
        case 'choiceMain': //选择申请单
          break
        case 'choiceDtl': //选择申请单明细
          userParam.viewKey = 'adm_matr_apply_item_for_auditadd'
          userParam.useMsg = '数据筛选条件：未参与准入审批的准入申请单明细'
          break
        case 'printDtl': //行打印
          global.utilPrint.open(global.printSet.admPrintDtl(this, para.data))
          break
        case 'printMain': //表头打印
          global.utilPrint.open(global.printSet.admPrintMain(this, para.data))
          break
      }
      if (para.button.key == 'printDtl' || para.button.key == 'printMain') return

      this.dtlAddType = para.button.key
      this.$refs.childDataViewAuditItem.editable = true
      this.$refs.childDataViewAuditItem.setEditQueries('applyBusKey', wrapper)
      this.$refs.childDataViewAuditItem.setEditUserParam('applyBusKey', userParam)
      this.$refs.childDataViewAuditItem.ocAddnew(null)
      setTimeout(() => {
        this.$refs.childDataViewAuditItem.editable = false
      }, 500)
    },
    //开始日期选择后
    bidDateChange(param) {
      this.$set(this.form, 'bidStartDate', this.bidDate[0])
      this.$set(this.form, 'bidEndDate', this.bidDate[1])
      this.propParent.ocAsynSaveViewForm()
    },
    //按钮操作
    btnsCLick(key, row) {
      switch (key) {
        case 1: //设置询价要求
          break;
        case 2: //查看询价结果
          break;
        case 3: //设置中标结果
          break;
      }

      this.form.applyId = row.applyId
      this.form.applyItemId = row.applyItemId
      this.form.auditId = this.form.id
      this.form.auditItemId = row.id
      this.form.auditKey = this.form.busKey
      this.form.opType = key

      //打开对应窗口
      this.$refs.childDataViewAuditItem.editable = false
      this.$refs.childDataViewAuditItem.ocAddnew(null)
      // this.$refs.childDataViewAuditItem.editable = true
    },
    //按钮禁用判断
    checkBtnsDisable(key, row) {
      if (key == 2) return false
      let { roleCodes = [], code } = this.utils.getCurrentUser()

      //询价要求按钮，具有设备科权限的并且流程节点处于设备科才可以操作
      if (key == 1 && this.form.flowStatus && this.form.flowStatus.indexOf('shebeike2') != -1 ) {
        //忽略管理员
        if (code == 'admin' ) return false
        if (roleCodes.includes('adm_bid_require')) {
          return false
        }
      }

      //中标结果按钮，具有分院长权限的并且流程节点处于分院长才可以操作
      if (key == 3 && this.form.flowStatus == 'fenyuanzhang') {
        //忽略管理员
        if (code == 'admin' ) return false
        if (roleCodes.includes('adm_bid_result')) {
          return false
        }
      }
      return true;
    },
    setBtnShowHide(valueTo) {
      let hidden = this.strings.defaultString(this.form.flowStatus,'start') != 'start'

      if (valueTo) {
        if ('start' == valueTo) {
          hidden = false
        } else {
          hidden = true
        }
      }
      this.$refs.childDataViewAuditItem.setButtonInvisible('view', 'choiceMain', hidden)
      this.$refs.childDataViewAuditItem.setButtonInvisible('view', 'choiceDtl', hidden)
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: async () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          let currentUser = this.utils.getCurrentUser()
          this.$set(this.form, 'busUser', currentUser.name)
          this.$set(this.form, 'deptId', currentUser.deptId)
          this.$set(this.form, 'deptName', currentUser.deptName)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDateTimePattern))
        } else {
          this.fetchDataAuditItem()
        }
        if (this.form.bidStartDate ) {
          this.bidDate = [this.form.bidStartDate, this.form.bidEndDate]
        }
        setTimeout(() => {
          if (!this.form.auditRemark)  this.$set(this.form, 'auditRemark', '同意')
        }, 500)


        this.$refs.auditEsign.setUserSign()
        this.setBtnShowHide()
      },
      afterSave: () => {
        that.propParent.fetchData()
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        //提交前，进行一些校验
        let base64 = that.$refs.auditEsign.getData()
        let auditRemark = that.form.auditRemark

        //设备科询价时，起止时间必须设置
        if (flowButtonKey == 'inquiryPush' && this.form.flowStatus &&  that.form.flowStatus.indexOf('shebeike2') != -1 && !that.form.bidStartDate ) {
          let { roleCodes = [], code } = that.utils.getCurrentUser()
          if (roleCodes.includes('dept_device') || code == 'admin') {
            that.$message.warning('请设置询价起止时间，再提交')
            that.$refs.bidDate.focus()
            return
          }
        }

        if (that.strings.isBlank(auditRemark)) {
          that.$message.warning('请填写审批意见，再提交')
          that.$refs.auditRemark.focus()
          return
        }

        if (!base64) {
          that.$message.warning('请先完成签名，再提交')
          return
        }
        let flowCommentForm = {
          comment: auditRemark,
          signBase64: base64
        }
        that.$set(that.propParent, 'flowCommentForm', flowCommentForm)
        return true
      },
      afterFlow: (flowButtonKey, that2, isOk) => {
        that.setBtnShowHide(flowButtonKey)

        setTimeout(() => {
          that.$refs.flowLog.reload()
          if (!that.form.auditRemark) that.$set(this.form, 'auditRemark', '同意')
        }, 500)

      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
  },
  computed: {
    //自定义列
    propCustomCols(){
      return [
        {
          name: 'btns',
          title: '询价及中标操作',
          cmode: 'extra',
          width: 350,
          queryType: 'none',
          noprint: 1
        }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
    height: 100%;
  }
</style>
